package org.jiucai.app.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.jiucai.appframework.base.spring.service.IDownloadService;

public abstract class DemoBaseDownLoadService extends DemoBaseService implements IDownloadService {
	

	public final void handleRequest(Map<String, Object> param, OutputStream out) {
		
		String filePath = String.valueOf("/tmp/demo"); 
		
		log.info("csv文件路径: "+filePath);
		
		if(!filePath.endsWith("/")){
			filePath += "/";
		}
		
		File f = new File(filePath);
		FileInputStream fis;
		try {
			fis = new FileInputStream(f);
			int bytesRead;
			byte[] buf = new byte[4 * 1024]; // 4K buffer
			while ((bytesRead = fis.read(buf)) != -1) {
				out.write(buf, 0, bytesRead);
			}
			out.flush();
			out.close();
			fis.close();
			
		} catch (FileNotFoundException e) {
			log.error("file not exists or download file name is null.");
		} catch (IOException e) {
			log.error("file dowload faild: " + ExceptionUtils.getFullStackTrace(e));
		}
	}

	/**
	 * 下载临时文件路径
	 * @return
	 */
	protected String getFileSavePath(){
		
		String basePath = "/tmp/demo/report";
		
		//为防止统一文件夹文件数目过多 ，固 分为：按月将产生的下载文件分离 格式为yyyy-mm-dd
		
		String ymd = dateFormater.format(System.currentTimeMillis());
		basePath += "/" + ymd;
		return basePath;
	}
	
	/**
	 * 返回下载文件的content-type
	 * @return
	 */
	protected String getDownloadFilContentType(){
		return "application/octet-stream";
	}
	
}
